import requests
import http.cookiejar as cookielib
import time,datetime
from lxml import etree
import webbrowser

#打开零件的单子
with open('part_numbers.txt','r') as f:
    part_numbers=f.readlines()


#设置代理
proxies={
'http':'proxy.mgmt.intern:80',
'https':'proxy.mgmt.intern:80'
}

#模拟浏览器头部文件
headers= {
    'authority': 'www.bomcheck.net',
    'cache-control': 'max-age=0',
    'sec-ch-ua': 'Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': "Windows",
    'upgrade-insecure-requests': '1',
    'origin': 'null',
    'content-type': 'application/x-www-form-urlencoded',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-user': '?1',
    'sec-fetch-dest': 'document',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
}

#登录账号等信息
data={
    'blu-token-key':'blu-login-token',
#    'blu-token':'169475075620bbe4a6f7ff3.26718944',
    'username':'woshishui',
    'password':'nihao',
    'submit':'Login',
   
    }

#链接等
url0='https://www.bomcheck.net'
#webbrowser.open(url0, new=0, autoraise=True)
url='https://www.bomcheck.net/zh/account/login'
url1='https://www.bomcheck.net/zh/account'
url2='https://www.bomcheck.net/zh/declaration/1995290'
url3='https://www.bomcheck.net/zh/parts/listing/summary?searchNumber='


#启动上网回话，并登录
session=requests.Session()
x=session.post(url,headers=headers,data=data,proxies=proxies,verify=False)

#输入之后要开的链接，以字典形式输出
def data(link_x):
    link=url3+link_x
    z=session.get(link,headers=headers,proxies=proxies,verify=False)
    print(z.status_code)
    tree = etree.HTML(z.text)
    #x=tree.xpath("//div[@class='declaration-detail']/ul/li/a/text")
    linkx=tree.xpath("//@href")
    def link1(x):
        for item in x:
            if "/zh/declaration" in item:
                return item
    #获取详细的声明文件页面地址
    #print(link1(linkx))
    url4=url0+link1(linkx)
    #url4=url2
    print(url4)
    #print(z.text)
    s=session.get(url4,headers=headers,proxies=proxies,verify=False)
    #print(s.status_code)
    #print(s.text)

    
    #日期格式改造，并计算出距今多少天
    def datex(datex):
        date0=[]
        for item in datex:
            #print('strat')
            #print(item)
            if item.replace('\n','').replace('\t','')=='':
                pass
            else:
                #print(item)
                item0=item.replace('\n','').replace('\t','')
                
                time_str = '18 Jun 2016'
                time_format=datetime.datetime.strptime(item0,'%d %b %Y')
                today=datetime.datetime.today()
                delta=str(today-time_format).split(' ')[0]
                t_str = time_format.strftime("%Y-%m-%d")
                date0.append([t_str,int(delta)])
                #print(t_str)
        return date0

    tree = etree.HTML(s.text)

    #x=tree.xpath("//fieldset[2]/table/tr/td/div/a/text()")
    #x=tree.xpath("//fieldset[2]/table/tr/td/div[starts-with(@class ,'evidence')]/attribute::*")
    #x=tree.xpath("//fieldset[2]/table/tr/td/div[starts-with(@class ,'evidence')]/div[@style='padding-top:5px']/text()")
    #x=tree.xpath("//fieldset[2]/table/tr/td/div[starts-with(@class ,'evidence')]/table/tr/td/span[@class='isRohsReport option no']")
    x_link=tree.xpath("//fieldset[2]/table/tr/td/div[starts-with(@class ,'evidence')]/table/tr/td/span[not(@class='isRohsReport option no')]/../../../../../../td/div/a/@href")
    x_text=tree.xpath("//fieldset[2]/table/tr/td/div[starts-with(@class ,'evidence')]/table/tr/td/span[not(@class='isRohsReport option no')]/../../../../../../td/div/a/text()")
    x_date=tree.xpath("//fieldset[2]/table/tr/td/div[starts-with(@class ,'evidence')]/table/tr/td/span[not(@class='isRohsReport option no')]/../../../../../../td/div[starts-with(@class ,'evidence')]/div[@style='padding-top:5px']/text()")
    #print(x_date)

    #print(x_link)
    #print(x_text)
    date1=datex(x_date)
    dict0={}
    len0=len(x_link)
    for i in range(len0):
        dict0[x_text[i]]={'part_number':link_x,'link':x_link[i],'date':date1[i][0],'delta':date1[i][1]}
    return dict0

#遍历所有部件号码
dict_result={}
for item in part_numbers:
    dict0=data(item)
    dict_result.update(dict0)
log=[]
for item in dict_result.keys():
    log.append([dict_result[item]['part_number'],item,dict_result[item]['link'],dict_result[item]['date'],dict_result[item]['delta']])

#生成结果网页
html_head='''

<html>

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="refresh" content="{}">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>Bootstrap 101 Template</title>

<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

<!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css" integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
      <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
  </head>

<body>
'''

#表格新写法 标题， 头head, 内容， 超链接， 超链接所在的列的排序号，以0开头，如果没有超链接和排序号就是默认普通的表格
def tab_htmls(title,headers0,rows,link=url0,link_id=2):
    start='''
    <table class="table table-condensed">
        <thead>
            <tr>
                <th>#</th>
                <th>Firstname</th>
                <th>2nname</th>
            </tr>
        </thead>
        '''
    headers='<body><h2>'+title+'</h2><table class="table table-bordered table-striped"><thead><tr>'
    for item in headers0:
        headers=headers+'<th>'+item+'</th>'
    headers=headers+'</tr></thead>'
    body='<tbody>'
    i=1
    for item in rows:
        body=body+'<tr>'
        i0=0
        for x in item:
            if i0==link_id:
                body=body+'<td><a href="{}{}">{}</a>'.format(link,str(x),str(x))+'</td>'
            else:
                body=body+'<td>{}'.format(str(x))+'</td>'
            i0=i0+1
        i=i+1
        body=body+'</tr>'
    body=body+'</tbody></table></body>'
    return headers+body
with open('a.htm','w',encoding='utf-8') as f:
    f.writelines(html_head+tab_htmls('结果展示',['零件编号','文件名','链接','创建日期','距今天数'],log))
urlx='a.htm'

#打开网页结果展示
webbrowser.open(urlx, new=0, autoraise=True)
